package pl.com.qapps.datastore;

import java.util.Objects;

import com.google.appengine.api.datastore.DatastoreFailureException;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entities;
import com.google.appengine.api.datastore.Key;

/**
 * 
 * @author Jakub Dykowski
 * 
 */
public class DatastoreUtils {

	private DatastoreUtils() {
	}

	public static boolean isDescendantOf(Key key, Key ancestor) {
		if (key.equals(ancestor))
			return true;
		Key parent = key.getParent();
		while (parent != null && !parent.equals(ancestor)) {
			parent = parent.getParent();
		}
		if (parent != null)
			return true;
		else
			return false;
	}

	/**
	 * Returns the entity group (root entity). Can be the key itself.
	 * 
	 * @param key
	 * @return root entity
	 * @throws IllegalArgumentException
	 *             if key is null
	 */
	public static Key getEntityGroup(Key key) throws IllegalArgumentException {
		if (key == null)
			throw new IllegalArgumentException(
					"NULL key cannot have a parent SILLY.");
		Key parent = key.getParent();
		if (parent == null)
			return key;
		while (parent != null) {
			parent = parent.getParent();
		}
		return parent;
	}

	public static void print(Iterable<Entities> entities) {

	}

	public static void copy(Datastore from, Datastore to)
			throws DatastoreFailureException {
		Objects.requireNonNull(from, "from cannot be null");
		Objects.requireNonNull(to, "to cannot be null");
		// TODO implement
		throw new UnsupportedOperationException("not supported yet");
	}

	public static void erase(Datastore toErase) {
		Objects.requireNonNull(toErase, "toErase cannot be null");
		DatastoreService service = toErase.getDatastoreService(null);
		// TODO implement
		throw new UnsupportedOperationException("not supported yet");
	}
}
